//
//  Utils.m
//  iShop
//
//  Created by svp on 1/6/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "Utils.h"
#import "FileCache.h"

@implementation Utils

+(UIImage*) getImageOf:(NSString*)kind withName:(NSString*)fileName
{
	//cache
	NSString *fileCache = [FileCache createCachePathForKey:fileName];
	if (![FileCache isCacheFileExist:fileCache]) {
		NSString* imageURL = [NSString stringWithFormat:@"%@/image/%@/%@",[Utils getHostAddress],kind,fileName];
		NSLog(@"imageURL:%@",imageURL);
		NSData *imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
		if (imagedata.length > 0) {
			[imagedata writeToFile:fileCache atomically:NO];
			return [UIImage imageWithData:imagedata];
		}
		else {
			return [UIImage imageNamed:[NSString stringWithFormat:@"%@_default.jpg",kind]];
		}
	}	
	return [UIImage imageWithData:[NSData dataWithContentsOfFile:fileCache]];
}

+(NSString*) getHostAddress
{
	NSString *hostAddress = [[NSUserDefaults standardUserDefaults] stringForKey:@"ADDRESSHOST"];
	
	if(!hostAddress)
	{
		[Utils registerDefaultsFromSettingsBundle];
		hostAddress = [[NSUserDefaults standardUserDefaults] stringForKey:@"ADDRESSHOST"];
	}
	return hostAddress;
	
}

+(void)registerDefaultsFromSettingsBundle {
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }
	
    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
	
    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for(NSDictionary *prefSpecification in preferences) {
        NSString *key = [prefSpecification objectForKey:@"Key"];
        if(key) {
            [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
        }
    }
	
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
    [defaultsToRegister release];
}

+(void) setValue:(NSObject*)value forRefKey:(NSString*)key
{
	NSUserDefaults *refs = [NSUserDefaults standardUserDefaults];
	NSLog(@"pre:%@--%@",key,[refs objectForKey:key]);
	if ([value isEqual:[NSNull null]]) {
		[refs removeObjectForKey:key];
	}
	else {
		[refs setValue:value forKey:key];
	}

	
	[refs synchronize];
	NSLog(@"after:%@--%@",key,[refs objectForKey:key]?[refs objectForKey:key]:@"AAAA");
}

+(NSObject*) getValueForRefKey:(NSString*)key
{
	
	NSLog(@"getValueForRefKey:%@--%@",key,[[NSUserDefaults standardUserDefaults] valueForKey:key]);
	return [[NSUserDefaults standardUserDefaults] valueForKey:key];
}

@end
